package com.guldan.jaina.manager;

import com.guldan.core.constants.CommonConstant;
import com.guldan.core.enums.CitizenUpdateTypeEn;
import com.guldan.core.enums.CitizenValidatingTypeEn;
import com.guldan.core.enums.ValidatingCitizenUpdateTypeEn;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.area.AreaDTO;
import com.guldan.jaina.dto.citizenbank.CitizenBankDTO;
import com.guldan.jaina.dto.citizenbatchupdate.CitizenBatchUpdateDTO;
import com.guldan.jaina.dto.citizenbatchupdate.CitizenBatchUpdateSearchDTO;
import com.guldan.jaina.dto.citizenfail.CitizenFailDTO;
import com.guldan.jaina.dto.citizeninfo.CitizenInfoDTO;
import com.guldan.jaina.utils.CitizenInfoDomainConvertUtils;
import com.guldan.jaina.utils.UserUtils;
import com.guldan.jaina.utils.validating.CheckIdCard;
import com.guldan.mapper.db.entity.*;
import com.guldan.mapper.db.mapper.CitizenBankMapperExt;
import com.guldan.mapper.db.mapper.CitizenBatchUpdateMapperExt;
import com.guldan.mapper.db.mapper.CitizenInfoMapperExt;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2016/12/26
 * Time: 14:58
 */
@Service
public class CitizenBatchUpdateManager extends BaseManager {


    @Autowired
    private CitizenBatchUpdateMapperExt citizenBatchUpdateMapperExt;

    @Autowired
    private CitizenInfoMapperExt citizenInfoMapperExt;

    @Autowired
    private CitizenBankMapperExt citizenBankMapperExt;

    @Autowired
    private CitizenBankManager citizenBankManager;

    @Autowired
    private CitizenInfoManager citizenInfoManager;

    @Autowired
    private AreaManager areaManager;

    //只有添加操作
    public CitizenBatchUpdateDTO save(CitizenBatchUpdateDTO dto) {

        CitizenBatchUpdate entity = new CitizenBatchUpdate();
        if (dto.getId() == null) {
            //entity.setId(entity.getId());
            entity.setBatchId(dto.getBatchId());
            entity.setOriName(dto.getOriName());
            entity.setName(dto.getName());
            entity.setIdentNumber(dto.getIdentNumber());
            entity.setCitizenInfoId(dto.getCitizenInfoId());

            if (UserUtils.getUser() != null) {
                entity.setCreatorAreaId(UserUtils.getUser().getAreaId());
                entity.setCreator(UserUtils.getUser().getUserAccount());
            } else {
                entity.setCreatorAreaId(dto.getCreatorAreaId());
                entity.setCreator(dto.getCreator());
            }

            entity.setBankCode(dto.getBankCode());
            entity.setBankName(dto.getBankName());
            entity.setBankNumber(dto.getBankNumber());
            entity.setNewAreaCode(dto.getNewAreaCode());
            entity.setFailReason(dto.getFailReason());
            entity.setType(dto.getType());
            entity.setIsSuccess(dto.getSuccess());
            entity.setCreateTime(DateUtil.getCurrentTime());

            citizenBatchUpdateMapperExt.insertSelective(entity);
        }

        return CitizenInfoDomainConvertUtils.convert(entity);
    }

    public Pagination<CitizenBatchUpdateDTO> list(CitizenBatchUpdateSearchDTO searchDTO) {

        Pagination<CitizenBatchUpdateDTO> result = new Pagination<CitizenBatchUpdateDTO>(searchDTO.getCurrentPage(), searchDTO.getPerPage());
        CitizenBatchUpdateExample example = buildSearchExample(searchDTO);
        int total = citizenBatchUpdateMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<CitizenBatchUpdateDTO> data = new ArrayList<CitizenBatchUpdateDTO>();
            List<CitizenBatchUpdate> list = citizenBatchUpdateMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (CitizenBatchUpdate entity : list) {
                CitizenBatchUpdateDTO dto = CitizenInfoDomainConvertUtils.convert(entity);

                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    //build查询Example
    private CitizenBatchUpdateExample buildSearchExample(CitizenBatchUpdateSearchDTO search) {
        CitizenBatchUpdateExample example = new CitizenBatchUpdateExample();
        CitizenBatchUpdateExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(search.getBatchId())) {
            criteria.andBatchIdEqualTo(search.getBatchId());
        }
        if (StringUtils.isNotBlank(search.getIdentNumber())) {
            criteria.andIdentNumberEqualTo(search.getIdentNumber());
        }
        if (StringUtils.isNotBlank(search.getName())) {
            criteria.andNameEqualTo(search.getName());
        }
        if (search.getType() != null && search.getType() > 0) {
            criteria.andTypeEqualTo(search.getType());
        }
        if (search.getSuccess() != null) {
            criteria.andIsSuccessEqualTo(search.getSuccess());
        }
        criteria.andIsDeleteEqualTo(false);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("id asc");
        }
        return example;
    }

    //获取上传批次id，和时间，list
    public List<CitizenBatchUpdateDTO> uploadBatchList(CitizenBatchUpdateSearchDTO search) {
        CitizenBatchUpdateExample example = new CitizenBatchUpdateExample();
        CitizenBatchUpdateExample.Criteria criteria = example.createCriteria();
        criteria.andCreatorAreaIdEqualTo(UserUtils.getUser().getAreaId());
        if (search.getType() != null && search.getType() > 0) {
            criteria.andTypeEqualTo(search.getType());
        }
        if (search.getSuccess() != null) {
            criteria.andIsSuccessEqualTo(search.getSuccess());
        }
        example.setOrderByClause("create_time desc");
        List<CitizenBatchUpdateDTO> dtoList = new ArrayList<>();
        List<CitizenBatchUpdate> entityList = citizenBatchUpdateMapperExt.seletUploadBatchList(example);

        if (entityList != null && entityList.size() > 0) {
            for (CitizenBatchUpdate entity : entityList) {
                dtoList.add(CitizenInfoDomainConvertUtils.convert(entity));
            }
        }
        return dtoList;
    }

    //批量更新姓名
    public Boolean batchUpdateName(CitizenBatchUpdateDTO dto) {
        Boolean ret = true;
        try {
            //验证身份证不能为空
            if (StringUtils.isBlank(dto.getIdentNumber()) || StringUtils.isBlank(dto.getName())) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_name, ValidatingCitizenUpdateTypeEn.infoCanNotNull);
                ret = false;
                return ret;
            }
            //验证是否存在该身份证号
            CitizenInfoExample example = new CitizenInfoExample();
            CitizenInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdentNumberEqualTo(dto.getIdentNumber());
            criteria.andIsDeleteEqualTo(false);
            List<CitizenInfo> list = citizenInfoMapperExt.selectByExample(example);
            if (list == null || list.size() == 0) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_name, ValidatingCitizenUpdateTypeEn.idCardNotFind);
                ret = false;
                return ret;
            } else {
                CitizenInfo update = new CitizenInfo();
                update.setName(dto.getName());
                update.setModifyTime(DateUtil.getCurrentTime());
                if (citizenInfoMapperExt.updateByExampleSelective(update, example) > 0) {
                    //更新成功，写入更新成功记录
                    writeSuccessUpdate(dto, CitizenUpdateTypeEn.citizen_name);
                    ret = true;
                    return ret;
                } else {
                    //更新失败，记录失败
                    writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_name, ValidatingCitizenUpdateTypeEn.unknow);
                    ret = false;
                    return ret;
                }
            }
        } catch (Exception ex) {
            logger.error("batchUpdateName fail" + ex.getMessage());
            ex.printStackTrace();
            ret = false;
        } finally {
            return ret;
        }

    }

    //批量更新卡号
    public Boolean batchUpdateBank(CitizenBatchUpdateDTO dto) {

        logger.info("++++++"+JSONObject.fromObject(dto).toString());
        Boolean ret = true;
        try {
            /*//验证身份证不能为空
            if (StringUtils.isBlank(dto.getIdentNumber()) || StringUtils.isBlank(dto.getBankName()) || StringUtils.isBlank(dto.getBankNumber())) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.idCardNotFind);
                ret = false;
                return ret;
            }*/

            //检查身份证格式
            CheckIdCard cic = new CheckIdCard(dto.getIdentNumber());
            if (!cic.checkLength()) {
                //校验身份长度是是否是15位or18位
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.idCardLengthError);
                ret = false;
                return ret;
            }
            if (!cic.validate()) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.idCardFormatError);
                ret = false;
                return ret;
            }

            //验证是否存在该身份证号
            CitizenInfoExample example = new CitizenInfoExample();
            CitizenInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdentNumberEqualTo(dto.getIdentNumber());
            criteria.andIsDeleteEqualTo(false);
            List<CitizenInfo> list = citizenInfoMapperExt.selectByExample(example);
            if (list == null || list.size() == 0) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.idCardNotFind);
                ret = false;
                return ret;
            } else {
                CitizenInfo citizenInfo = list.get(0);


                //验证银行名称是否存在
                String bankCode = citizenInfoManager.getDicCodeByTypeAndValue(CommonConstant.DIC_TYPE_BANKCODE, dto.getBankName());
                if (StringUtils.isBlank(bankCode)) {
                    writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.bankNotFind);
                    ret = false;
                    return ret;
                }
                dto.setBankCode(bankCode);

                //验证卡号是否已经存在
                CitizenBankExample bankExample = new CitizenBankExample();
                CitizenBankExample.Criteria bankCriteria = bankExample.createCriteria();
                bankCriteria.andBankNumberEqualTo(dto.getBankNumber());
                bankCriteria.andIsDeleteEqualTo(false);

                List<CitizenBank> bankList = citizenBankMapperExt.selectByExample(bankExample);
                if (bankList != null && bankList.size() > 0) {
                    //卡号已经存在
                    //再验证是否是当前用户的


                    CitizenInfoDTO ci = citizenInfoManager.get(bankList.get(0).getCitizenInfoId());
                    String failReason = String.format(ValidatingCitizenUpdateTypeEn.bankNumberIsUsed.getMean(), ci.getName(), ci.getAreaName());
                    writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, failReason);
                    ret = false;
                    return ret;
                    /*
                    if (bankList.get(0).getCitizenInfoId().intValue() != citizenInfo.getCitizenInfoId().intValue()) {
                        //不是当前用户的卡号，则提示已经被使用
                        String failReason = String.format(ValidatingCitizenUpdateTypeEn.bankNumberIsUsed.getMean(), ci.getName(), ci.getAreaName());
                        writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, failReason);
                        ret = false;
                        return ret;
                    } else {
                        //校验已经存在的 卡号，和 bankCode是否一致
                        if (bankList.get(0).getBankCode().equals(bankCode)) {
                            String failReason = String.format(ValidatingCitizenUpdateTypeEn.bankNumberIsUsed.getMean(), ci.getName(), ci.getAreaName());
                            writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, failReason);
                            ret = false;
                            return ret;
                        }
                    }*/
                }


                //验证开户行是否已经存在
                bankExample = new CitizenBankExample();
                bankCriteria = bankExample.createCriteria();
                bankCriteria.andCitizenInfoIdEqualTo(citizenInfo.getCitizenInfoId());
                bankCriteria.andBankCodeEqualTo(dto.getBankCode());
                bankCriteria.andIsDeleteEqualTo(false);

                bankList = citizenBankMapperExt.selectByExample(bankExample);
                if (bankList == null || bankList.size() == 0) {
                    //用户存在该银行的卡，则新增加
                    CitizenBankDTO citizenBank = new CitizenBankDTO();
                    citizenBank.setCitizenInfoId(citizenInfo.getCitizenInfoId());
                    citizenBank.setBankCode(dto.getBankCode());
                    citizenBank.setBankNumber(dto.getBankNumber());
                    citizenBankManager.save(citizenBank);
                } else {
                    //已经存在该银行的卡，则更新卡号
                    CitizenBankDTO citizenBank = CitizenInfoDomainConvertUtils.convert(bankList.get(0));
                    citizenBank.setBankNumber(dto.getBankNumber());
                    citizenBankManager.save(citizenBank);
                }
                writeSuccessUpdate(dto, CitizenUpdateTypeEn.citizen_bank);
                ret = true;
                return ret;
            }
        } catch (Exception ex) {
            logger.error("batchUpdateBank fail" + ex.getMessage());
            ex.printStackTrace();
            writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_bank, ValidatingCitizenUpdateTypeEn.unknow);
            ret = false;

        } finally {
            return ret;
        }
    }

    //批量更新区划
    public Boolean batchUpdateArea(CitizenBatchUpdateDTO dto) {
        Boolean ret = true;
        try {

            //检查身份证格式
            CheckIdCard cic = new CheckIdCard(dto.getIdentNumber());
            if (!cic.checkLength()) {
                //校验身份长度是是否是15位or18位
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.idCardLengthError);
                ret = false;
                return ret;
            }
            if (!cic.validate()) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.idCardFormatError);
                ret = false;
                return ret;
            }

            //验证是否存在该身份证号
            CitizenInfoExample example = new CitizenInfoExample();
            CitizenInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIdentNumberEqualTo(dto.getIdentNumber());
            criteria.andIsDeleteEqualTo(false);
            List<CitizenInfo> list = citizenInfoMapperExt.selectByExample(example);
            if (list == null || list.size() == 0) {
                writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.idCardNotFind);
                ret = false;
                return ret;
            } else {

                //校验区划代码是否存在
                AreaDTO areaDTO = areaManager.checkExistReturnDTO(dto.getNewAreaCode());
                if (areaDTO == null) {
                    writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.areaCodeNotFind);
                    ret = false;
                    return ret;
                }

                CitizenInfo update = new CitizenInfo();
                update.setAreaId(areaDTO.getAreaId());
                update.setModifyTime(DateUtil.getCurrentTime());
                if (citizenInfoMapperExt.updateByExampleSelective(update, example) > 0) {
                    //更新成功，写入更新成功记录
                    writeSuccessUpdate(dto, CitizenUpdateTypeEn.citizen_area);
                    ret = true;
                    return ret;
                } else {
                    //更新失败，记录失败
                    writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.unknow);
                    ret = false;
                    return ret;
                }
            }
        } catch (Exception ex) {
            logger.error("batchUpdateArea fail" + ex.getMessage());
            ex.printStackTrace();
            writeFailUpdate(dto, CitizenUpdateTypeEn.citizen_area, ValidatingCitizenUpdateTypeEn.unknow);
            ret = false;

        } finally {
            return ret;
        }
    }


    //写入失败记录
    public Boolean writeFailUpdate(CitizenBatchUpdateDTO dto, CitizenUpdateTypeEn citizenUpdateTypeEn, ValidatingCitizenUpdateTypeEn validatingCitizenUpdateTypeEn) {
        dto.setSuccess(false);
        //dto.setCreatorAreaId(UserUtils.getUser().getAreaId());
        dto.setType(citizenUpdateTypeEn.getCode());
        dto.setFailReason(validatingCitizenUpdateTypeEn.getMean());
        save(dto);
        return true;
    }

    //写入失败记录
    public Boolean writeFailUpdate(CitizenBatchUpdateDTO dto, CitizenUpdateTypeEn citizenUpdateTypeEn, String failReason) {
        dto.setSuccess(false);
        //dto.setCreatorAreaId(UserUtils.getUser().getAreaId());
        dto.setType(citizenUpdateTypeEn.getCode());
        dto.setFailReason(failReason);
        save(dto);
        return true;
    }

    //写入成功记录
    public Boolean writeSuccessUpdate(CitizenBatchUpdateDTO dto, CitizenUpdateTypeEn citizenUpdateTypeEn) {
        Boolean ret = true;
        try {
            dto.setSuccess(true);
            dto.setType(citizenUpdateTypeEn.getCode());
            save(dto);
        } catch (Exception ex) {
            ret = false;
        } finally {
            return true;
        }
    }


}
